<template>
  <div>
    <h3>工具借还管理</h3>
    <el-form :model="form" inline :rules="inlineRules" ref="form">
      <el-form-item label="员工编号" prop="empno">
        <el-input v-model="form.empno" placeholder="请输入员工编号"></el-input>
      </el-form-item>
      <el-form-item label="飞机注册号" prop="airplane">
        <el-select v-model="form.airplane" placeholder="请选择飞机注册号">
          <el-option
            v-for="item in airplane"
            :label="item.airplane"
            :value="item.airplane"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="借用/归还数量" prop="toolnum">
        <el-input-number
          v-model="form.toolnum"
          placeholder="请输入借用/归还数量"
        ></el-input-number
      ></el-form-item>
      <el-form-item label="工具编号" prop="barcode">
        <el-input v-model="form.barcode" placeholder="请输入工具编号"></el-input
      ></el-form-item>
    </el-form>
    <el-button type="primary" @click="borrow('form')">提 交</el-button>
    <el-button type="primary" @click="print">打 印</el-button>
    <el-table :data="tableData">
      <el-table-column label="工具名称" prop="toolName"></el-table-column>
      <el-table-column label="工具编号" prop="barcode"></el-table-column>
      <el-table-column label="飞机注册号" prop="airplaneId"></el-table-column>
      <el-table-column label="借用时间" prop="borrowTime"></el-table-column>
      <el-table-column label="借用数量" prop="borrowCount"></el-table-column>
      <el-table-column label="已归还数量" prop="returnCount"></el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <div v-show="false" width="80%">
      <div id="printBox">
        <table>
          <thead>
            <tr>
              <td colspan="8">
                <h1 style="text-align: left; margin: 10px 0">借还明细清单</h1>
              </td>
            </tr>
            <tr style="font-weight: bold">
              <td style="width: 40px">序号</td>
              <td style="width: 220px">工具名称</td>
              <td style="width: 100px">工具编号</td>
              <td style="width: 90px">借用人</td>
              <td style="width: 100px">飞机注册号</td>
              <td style="width: 190px">借用时间</td>
              <td style="width: 80px">借用数量</td>
              <td style="width: 90px">已归还数量</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(tool, index) in gridData" :key="index">
              <td>{{ index + 1 }}</td>
              <td>{{ tool.toolName }}</td>
              <td>{{ tool.barcode }}</td>
              <td>{{ tool.name }}</td>
              <td>{{ tool.airplaneId }}</td>
              <td>{{ tool.borrowTime }}</td>
              <td>{{ tool.borrowCount }}</td>
              <td>{{ tool.returnCount }}</td>
            </tr>
          </tbody>
          <tfoot>
            <tr>
              <td colspan="8">
                <h2 style="text-align: left; margin: 10px 0">清点人：</h2>
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import airplaneApi from "@/api/airplane/index";
import borrowApi from "@/api/borrow/index";
import detail from "@/views/borrow/detail.vue";
import store from "@/store/index";
import { verifyBarcode } from "@/utils/verify/verify";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: { detail },
  props: {},
  data() {
    const validateNum = (rule, value, callback) => {
      // 使用正则表达式进行匹配
      // 匹配数字开头，后面跟着九个数字，且开头不为0
      if (value % 1 !== 0) {
        callback(new Error("借用数量必须是一个整数！"));
      } else if (value <= 0) {
        callback(new Error("借用数量不得小于1！"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      gridData: [], //用于给打印显示的页面
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      form: {
        empno: "",
        airplane: "",
        toolnum: "",
        barcode: "",
      },
      airplane: [],
      inlineRules: {
        airplane: [
          { required: true, message: "请输入飞机注册号", trigger: "blur" },
        ],
        empno: [{ required: true, message: "请输入员工编号", trigger: "blur" }],
        toolnum: [{ required: true, trigger: "blur", validator: validateNum }],
        barcode: [
          { required: true, message: "请输入工具编号", trigger: "blur" },
        ],
      },
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {
    form: {
      handler(newVal, oldVal) {
        if (newVal.empno.length == 4 && newVal.barcode.length == 9) {
          this.$nextTick(() => {
            this.$refs.form.validate((valid) => {
              if (valid) {
                this.toolManage();
              } else {
                this.form.barcode = "";
              }
            });
          });
        } else {
          if (newVal.empno.length == 4) {
            this.refreshList(1);
          }
          // 在这里处理属性变化
          if (newVal.barcode.length == 9) {
            this.$nextTick(() => {
              this.$refs.form.validate((valid) => {
                if (valid) {
                  this.toolManage();
                } else {
                  this.form.barcode = "";
                }
              });
            });
          }
        }
      },
      deep: true, // 深度监视
    },
  },
  //方法集合
  methods: {
    print() {
      if (!this.form.empno) {
        this.$message({
          message: "工号为空时不支持打印！",
          type: "error",
        });
        return;
      } else {
        //获取待打印的清单
        borrowApi.printPage(this.form.empno)
      }
    },
    toolManage() {
      if (verifyBarcode(this.form.barcode, this)) {
        const name = store.getters.name;
        let data = this.form;
        data.name = name;
        borrowApi
          .borrowOrReturn(data)
          .then((res) => {
            this.$message({
              message: `${res.message}`,
              type: "success",
            });
            //刷新子组件的数据
            this.refreshList(1);
            this.form.barcode = "";
          })
          .catch((err) => {
            this.form.barcode = "";
          });
      }
    },
    borrow: async function (form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.toolManage();
        }
      });
    },
    handleCurrentChange: async function (currentPage) {
      this.switch_type = true;
      this.list(currentPage);
    },
    list(currentPage) {
      borrowApi
        .list(currentPage, this.pageSize, this.form.empno)
        .then((res) => {
          this.tableData = res.data;
          this.currentPage = currentPage;
        });
    },
    getTotal() {
      borrowApi.total(this.form.empno).then((res) => {
        this.total = res.data;
      });
    },
    refreshList(currentPage) {
      this.getTotal();
      this.list(currentPage);
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    airplaneApi.all().then((res) => {
      this.airplane = res.data;
    });
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped>
.custom-input {
  width: 150px;
}
thead {
  display: table-header-group; /* 这个属性使thead总是在新的page-break之后重新开始 */
}
</style>
